package com.lhcai.lc.category.matrix;

import java.util.Arrays;

/**
 * 2326. 螺旋矩阵 IV
 *
 * @author liuhuaicai
 * @since 2025-01-04 22:06
 */
public class Lc2326 {
    /**
     * 1、一步步遍历，撞墙转向
     * 2、一行、一列的遍历，缩小内径
     * @param m m
     * @param n n
     * @param head head
     * @return  int[][]
     */
    public int[][] spiralMatrix(int m, int n, ListNode head) {
        int[][] res = new int[m][n];
        Arrays.stream(res).forEach(a -> Arrays.fill(a, -1));
        // 方向数组
        int[][] dir = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        // 当前方向
        int curIndex = 0;
        int row = 0;
        int col = 0;
        for (ListNode node = head; node != null; node = node.next) {
            res[row][col] = node.val;
            int nextRow = row + dir[curIndex][0];
            int nextCol = col + dir[curIndex][1];
            if (nextRow < 0 || nextCol < 0 || nextRow >= m || nextCol >= n || res[nextRow][nextCol] != -1) {
                curIndex = (curIndex + 1) % 4;
            }
            row += dir[curIndex][0];
            col += dir[curIndex][1];
        }
        return res;
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
